package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.query.CarPackageAuditQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private TaskService taskService;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<>(carPackageAuditMapper.selectForList(qo));
    }


    @Override
    public void save(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.insert(carPackageAudit);
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(CarPackageAudit carPackageAudit) {

        carPackageAuditMapper.updateByPrimaryKey(carPackageAudit);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            carPackageAuditMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<CarPackageAudit> list() {
        return carPackageAuditMapper.selectAll();
    }

    @Override
    @Transactional
    public InputStream getProcessByStream(Long id) {
        //获取审核对象
        CarPackageAudit audit = this.get(id);
        //通过审核对象获取流程实例ID
        String instanceId = audit.getInstanceId();
        List<String> activeActivity = null;
        //合理化校验,如果是审核中,返回activeActivity
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {

            activeActivity = runtimeService.getActiveActivityIds(instanceId);

        } else {
            activeActivity = new ArrayList<>();
        }
        //流程定义ID
        BpmnInfo bpmnInfo = bpmnInfoService.get(audit.getBpmnInfoId());
        //
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        DefaultProcessDiagramGenerator generator = new DefaultProcessDiagramGenerator();
        return generator.generateDiagram(bpmnModel, activeActivity,
                Collections.EMPTY_LIST, "微软雅黑",
                "微软雅黑", "微软雅黑");

    }

    @Override
    public void cancelApply(Long id) {
        //获取CarPackageAudit 对象
        CarPackageAudit audit = this.get(id);
        //设置审核状态为审核撤销
        carPackageAuditMapper.changeAuditStatus(id, CarPackageAudit.STATUS_CANCEL);
        //设置服务表状态为初始化
        serviceItemService.changeAuditStatus(audit.getServiceItemId(), ServiceItem.AUDITSTATUS_INIT);
        //删除流程定义
        runtimeService.deleteProcessInstance(audit.getInstanceId(), "撤销审核");
    }

    @Override
    @Transactional
    public void audit(Long id, Integer auditStatus, String info) {
        //获取审核对象
        CarPackageAudit audit = this.get(id);
        //合理化校验
        //流程处于审批中才可以进行操作
        if (audit == null || !CarPackageAudit.STATUS_IN_ROGRESS.equals(audit.getStatus())) {
            throw new BusinessException("只有处于审核状态的记录才能进行审核操作");
        }
        //只有是受理人才有权限审批
        String userName = ShiroUtils.getUser().getUserName();
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            info = userName + "[同意],批注意见:" + info;

        } else {
            info = userName + "[拒绝],批注意见:" + info;
        }
        //设置info 字段的值
        audit.setInfo(audit.getInfo() + "</br>" + info);
        //查询任务
        Task currentTask = taskService.createTaskQuery().
                processInstanceId(audit.getInstanceId()).singleResult();
        //设置auditStatus的值
        taskService.setVariable(currentTask.getId(), "auditStatus", auditStatus);

        taskService.addComment(currentTask.getId(),audit.getInstanceId(),info);
        //完成任务
        taskService.complete(currentTask.getId());

        //下一个节点
        Task nextTask = taskService.createTaskQuery().
                processInstanceId(audit.getInstanceId()).singleResult();

        //根据STATUS_PASS 判断是审核通过或审核拒绝
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            if (nextTask != null) {
                //说明还有下一个节点,财务审核
                //设置
                audit.setAuditorId(Long.parseLong(nextTask.getAssignee()));
                audit.setAuditTime(new Date());

            } else {
                audit.setAuditorId(null);
                //审核通过
                //设置发起审核的记录状态为审核通过
                serviceItemService.updateAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_APPROVED);
                //设置审核状态为通过
                audit.setStatus(CarPackageAudit.STATUS_PASS);

            }

            }else {
            audit.setAuditorId(null);
            //审核拒绝
            //设置审批记录状态为重新调整
            serviceItemService.updateAuditStatus(audit.getServiceItemId(),ServiceItem.AUDITSTATUS_REPLY);
            //更新审核对象信息中的状态为审核拒绝
            audit.setStatus(CarPackageAudit.STATUS_REJECT);

        }

        //更新数据库中的审核对象信息
        carPackageAuditMapper.updateByPrimaryKey(audit);


    }
}

